from kubernetes import client, config

class KubernetesManager:
    def __init__(self):
        config.load_kube_config()
        self.v1 = client.CoreV1Api()
        self.api_instance = client.AppsV1Api()
        self.api_instance.delete_namespaced_deployment
    def create_deployment_and_service(self, namespace, container_name):
        # 创建 Deployment
        deployment_manifest = {
            'apiVersion': 'apps/v1',
            'kind': 'Deployment',
            'metadata': {
                'name': f'{container_name}-app'
            },
            'spec': {
                'replicas': 1,
                'selector': {
                    'matchLabels': {
                        'app': f'{container_name}-app'
                    }
                },
                'template': {
                    'metadata': {
                        'labels': {
                            'app': f'{container_name}-app'
                        }
                    },
                    'spec': {
                        'containers': [
                            {
                                'name': f'{container_name}-container',
                                'image': '172.20.216.103:8998/big_data_image/python:24.3.11',
                                'ports': [
                                    {
                                        'containerPort': 80
                                    }
                                ]
                            }
                        ],
                        'imagePullSecrets': [
                            {
                                'name': 'harbor-secret'
                            }
                        ]
                    }
                }
            }
        }

        try:
            self.api_instance.read_namespaced_deployment(name=deployment_manifest['metadata']['name'], namespace=namespace)
            print(f"Deployment '{deployment_manifest['metadata']['name']}' 已经存在.")
        except client.exceptions.ApiException as e:
            if e.status == 404:
                resp = self.api_instance.create_namespaced_deployment(body=deployment_manifest, namespace=namespace)
                print("Deployment created. status='%s'" % resp.status)
            else:
                raise e

        # 创建 Service
        service_manifest = {
            'apiVersion': 'v1',
            'kind': 'Service',
            'metadata': {
                'name': f'{container_name}-service'
            },
            'spec': {
                'selector': {
                    'app': f'{container_name}-app'
                },
                'ports': [
                    {
                        'protocol': 'TCP',
                        'port': 80,
                        'targetPort': 80
                    }
                ],
                'type': 'LoadBalancer'
            }
        }

        try:
            self.v1.read_namespaced_service(name=service_manifest['metadata']['name'], namespace=namespace)
            print(f"Service '{service_manifest['metadata']['name']}' 已经存在.")
        except client.exceptions.ApiException as e:
            if e.status == 404:
                resp = self.v1.create_namespaced_service(body=service_manifest, namespace=namespace)
                print("Service created. status='%s'" % resp)
            else:
                raise e

# 创建 KubernetesManager 实例
if __name__ == '__main__':
    k8s_manager = KubernetesManager()

    # 使用不同的命名空间和容器名称创建容器
    namespace = 'default'
    container_name = 'homework-1-20204249'
    k8s_manager.create_deployment_and_service(namespace, container_name)
